<!--
* description: 新增编辑-备件奖励单编辑
* author: xiaochengzuan
* createdDate: 2021-1-21
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter(o => o.isMust === true)"
            :ref=" comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :text="formField[comp.textField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :show-placeholder="comp.placeholder"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 24"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObject"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/views/pa/financialManagement/sparePartsBonusOperation/api';
export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    mixButton: () => import('@/components/basicComponent/mixButton')
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },
  created() {
  },
  mounted() {
    if (this.popupsState === 'add') {
      this.getCode()
    }
    this.setDisabled()
  },
  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save') /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.close(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '奖励单号：',
              codeField: 'bonusOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true,
              span: 8
            },
            {
              compKey: 'comKey3',
              labelName: '网点名称：',
              codeField: 'dlrCode',
              textField: 'dlrShortName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMust: true,
              isRequire: true,
              dataToObject: {
                oFields: 'dlrCode,dlrShortName',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                returnField: {
                  prop: 'dlrShortName',
                  label: '网点名称'
                },
                api: api.queryOrgDlrCodes
              },
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              disabled: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '奖励种类: ',
              codeField: 'bonusTypeId',
              textField: 'bonusTypeName',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                listQuery: { },
                api: {
                  APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusTypes.do',
                  ServiceCode: 'queryBonusTypes'
                },
                selectType: '1'
              },
              oFields: 'bonusTypeId,bonusTypeName',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey6',
              labelName: '奖励项目：',
              codeField: 'bonusItemId',
              textField: 'bonusItemName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'bonusItemId,bonusItemName',
              parentFileds: 'disabled:bonusTypeId-bonusItemId--false,value:bonusTypeId',
              customObj: {
                listQuery: { bonusTypeId: ''},
                api: {
                  APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusItemType.do',
                  ServiceCode: 'queryBonusItems'
                },
                selectType: '1'
              },
              type: 'dropdownList',
              disabled: true,
              // isMul: true,
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '奖励金额：',
              codeField: 'bonusAmount',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isRequire: true,
              span: 8,
              validrule: {
                // 保留一到两位小数
                isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/,
                resectMessage: {
                  isformat: '请输入正确的价格，金额最多保留两位小数!'
                }
              }
            },
            {
              compKey: 'compKey8',
              labelName: '申述截止时间：',
              codeField: 'appealDeadline',
              component: () => import('@/components/org/datePicker/datePicker'),
              type: 'datePicker',
              isMul: false,
              isMust: true,
              isRequire: true,
              span: 8
            }
          ],

      // 标题
      textMap: {
        edit: '备件奖励单编辑',
        add: '备件奖励单新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {
        bonusOrderCode: '',
        dlrCode: '',
        dlrShortName: '',
        bonusTypeId: '',
        bonusTypeName: '',
        bonusItemId: '',
        bonusItemName: '',
        bonusAmount: '',
        appealDeadline: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  methods: {
    getCode() {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBounsOrderCode.do',
        variables: { }
      }).then(r => {
        console.log(r)
        this.formField.bonusOrderCode = r['rows'][0]['bonusOrderCode']
      }).catch(err=> {})
    },
    // 编辑状态设置禁用
    setDisabled() {
      if (this.popupsState === 'edit') {
        const Field = this.tableComponents.filter(o => o['codeField'] === 'bonusOrderCode')[0]
        Field.disabled = true
      }
    },
    // 关闭弹窗
    closeEdit() {
      this.$emit('update:curPopupsVisible', false)
    },
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this
      const { bonusOrderId,updateControlId } = this.dynamicEditRowData
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          ServiceCode: 'editBonusOrderMake',
          APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/editBonusOrderMake.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          ...that.formField,
          bonusOrderId, updateControlId
        }

        // variables: {
        //   bonusOrderId: [],
        //   updateControlId: []
        // }

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: this.$t('sys.tips.esTip5') /* 保存成功*/,
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '保存失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        this.curPopupsVisible = false
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          ServiceCode: 'addBonusOrderMake',
          APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/addBonusOrderMake.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: '添加成功',
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message:
              '添加失败:' + response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        this.curPopupsVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan{
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

